package com.yjzx.util.common.util.encrypt;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;

/**
 * @author yjzx
 * @date 2024/06/04
 * @description HmacMd5
 */
public class HmacMd5 {

    /**
     * 算法 HmacMD5
     */
    private static final String KEY_MD5 = "HmacMD5";

    /**
     * @param data      要签名的内容
     * @param sigSecret 签名秘钥
     * @return 签名
     */
    public static String createSign(String data, String sigSecret) {
        try {
            SecretKey secretKey = new SecretKeySpec(sigSecret.getBytes(), KEY_MD5);
            Mac mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
            byte[] b = mac.doFinal(data.getBytes(Charset.forName(AES.ENCODE)));
            return bytesToHexString(b);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 字节转16进制 字母大写
     * @param b MD5加密签名后的byte数组
     * @return 转成64进制字符串
     */
    private static String bytesToHexString(byte[] b) {
        StringBuilder sb = new StringBuilder(b.length * 2);
        for (byte b1 : b) {
            int v = b1 & 0xff;
            if (v < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(v));
        }
        String sig = sb.toString();
        return sig.toUpperCase();
    }

}
